<?php
namespace Mentees\Controller;

class ChatController extends MainController {

    public function index(){
        $toid=$this->userID;
        $map['toID']=$toid;
        $obj=M("Chat");
        $listcount= $obj->field('id')->group('fromID')->where($map)->select(); 
        $count =count($listcount);
        import("Common.ORG.Page");
        $page = new \Page($count, 20);
        $show = $page->show();
        $list= $obj->field('id,fromID,fromName,fromFace,createTime')->group('fromID')->where($map)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select(); 
        foreach ($list as $key => $value) {
            $map['fromID']=$value['fromID'];
             $map['isread']=0;
            $list[$key]['total']=M("Chat")->where($map)->count();

            $list[$key]['type']=M("Member")->where("userid=".$value['fromID']."")->getField("userType");
        }
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    public function view(){
        $fromID=I("formID");
        $toID=$this->userID;
        if($fromID==""){
            $this->error(L("_parm_error"));
        }else{
            $where="((toID=".$toID." and fromID=".$fromID.") or (fromID=".$toID." and toID=".$fromID."))"; 
            $obj=M("Chat");
            $count =$obj->where($where)->count();
            import("Common.ORG.Page");
            $page = new \Page($count, 20);
            $show = $page->show();
            $list= $obj->where($where)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select(); 
            foreach ($list as $key => $value) {
               if($value['toID']==$toID){
                   $list[$key]['type']=0;
               }else{
                   $list[$key]['type']=1;
               }
               $paixu[$key] = $value['id'];
            }
            array_multisort($paixu,SORT_ASC, $list);
            $this->assign('list', $list);
            $this->assign('page', $show);
            $this->display();
        }
    }
}